package com.pomr.service.synthesize.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.synthesize.EquipmentDao;
import com.pomr.model.synthesize.Equipment;
import com.pomr.service.synthesize.EquipmentService;
import com.pomr.util.common.ChineseCharToEn;
import com.pomr.util.page.Page;
@Service
public class EquipmentServiceImpl implements EquipmentService{
	@Autowired
	@Qualifier("equipmentDaoImpl")
	private EquipmentDao equipmentDao;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean saveEquipment(Equipment equipment) throws Exception {
		equipment.setCreateTime(new Date());
		if(equipmentDao.add(equipment)){
			return true;
		}
		return false;
	}

	@Override
	public Page<List<Equipment>> searchEquipmentsByCondition(String name, String page, String limit)
			throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from Equipment ");
		int i=0;
		if(name!=null && !name.equals("")){
			i++;
			sb.append("where name like '%"+name+"%' ");
		}
		String hqlStr = sb.toString();
		Page<List<Equipment>> p = new Page<List<Equipment>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		return equipmentDao.showPage(hqlStr, "select count(1) "+hqlStr, p);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteEquipmentsByIds(String[] ids) throws Exception {
		int len = ids.length;
		String id = null;
		for(int i=0; i<len; i++){
			id = ids[i];
			if(id!=null && !id.equals("")){
				String hql = "delete from Equipment where id="+id;
				if(!equipmentDao.remove(hql)){
					throw new Exception("删除失败，id："+id);
				}else{
					//TODO 删除成功后 先出与之相关联的其他信息（如果存在入库或者其他信息不能删除）
				}
			}
		}
		return true;
	}

	@Override
	public Equipment searchEquipmentById(String id) throws Exception {
		String hql = "from Equipment where id = "+id;
		List<Equipment> list = equipmentDao.findByHql(hql);
		if(list == null || list.size()<=0){
			return null;
		}
		return list.get(0);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editEquipmentById(Equipment equipment) throws Exception {
		String hql = "update Equipment set ";
		int i = 0;
		if(equipment.getStatus() != null){
			hql += "status = '"+equipment.getStatus()+"'";
			i++;
		}
		if(equipment.getRemark()!=null){
			if(i == 0){
				hql += "remark='"+equipment.getRemark()+"'";
			}else{
				hql += ",remark='"+equipment.getRemark()+"'";
			}
		}
		hql += " where id = "+equipment.getId();
		//TODO 如果状态改变 改变相关联的状态
		return equipmentDao.editHql(hql);
	}

	@Override
	public List<Equipment> searchAllEquipment() throws Exception {
		return equipmentDao.findByHql("from Equipment where (status=null or status!='1')");
	}

}
